//
//  XFUserAccess.swift
//  SinaBlog
//
//  Created by macs on 15/11/9.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

import UIKit

//归档,解档,遵守协议,实现方法

class UserAccess: NSObject,  NSCoding {
    
    var avatar_large : String?
    var name :String?
    var access_token : String?
    var expires_in : NSTimeInterval = 0 {
        didSet {
            
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
            //print(expires_date)
        }
    }
  
//用来记录access_token的有效期
    var expires_date : NSDate?
    
    var uid : String?
    
    init(dict : [String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        //过滤
    }
    
    //重写 description 方法
  override var description : String {
    
        let keys = ["access_token","expires_in","uid","expires_date","avatar_large","name"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    //归档操作
    func savAccess () {
        //获取沙盒 Document路径
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("access.plist")
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //解档操作
    class func loadAccess () -> UserAccess? {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("access.plist")
//        print(path)
        if let access = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccess {
            //判断access_token是否过期
            if access.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return access
            }
        }
        
        return nil
    }
    
   
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_date,forKey: "expires_date")
        
    }
    
}
